注意:qt和c++编译器不一样
这段代码能来一个说一下吗?
void setNum(int derivednum1, int derivednum2, int derivednum3)
{
derivednum1 = derivednum1;
derivednum2 = derivednum2;
derivednum3 = derivednum3;
}
全部代码:
#include<iostream>
using namespace std;
class Base
{
public:
int basenum1;
private:
int basenum2;
protected:
int basenum3;
public:
//在类的内部,通过类成员方法或友元函数,各成员均可访问
void setNum(int a, int b, int c)
{
basenum1 = a;
basenum2 = b;
basenum3 = c;
}
friend void print(Base& b);//声明友元函数
void getnum()
{
cout << basenum1 << basenum2 << basenum3 << endl;
}
};
void print(Base& b) {//定义友元函数,非类成员函数,可实现类外访问
cout << b.basenum1 << " " << b.basenum2 << " " << b.basenum3 << endl;
}
class Derived : public Base {
public:
int derivednum1;
private:
int derivednum2;
protected:
int derivednum3;
public:
//在派生类内部只能访问基类的public成员和protected成员,不能访问基类的private成员
//不看派生类的继承方式
void setNum(int derivednum1, int derivednum2, int derivednum3)
{
derivednum1 = derivednum1;
derivednum2 = derivednum2;
derivednum3 = derivednum3;
}
friend void print(Derived& d)
{
d.basenum1 = 10;
//d.basenum2 = 17;//基类的私有成员,在派生类中不可访问
d.basenum3 = 15;
cout << d.derivednum1 << " " << d.derivednum2 << " " << d.derivednum3 << endl;
}
};
class Derived1 : private Base {
public:
void print()
{
//basenum2 = 10; //基类的私有成员,在派生类中不可访问
cout << basenum1 << " " << basenum3 << endl; //基类的公有成员和保护成员,在派生类中 //可访问
}
};
class Derived2 : protected Base
{
public:
void print()
{
//basenum2 = 10; //基类的私有成员,在派生类中不可访问
cout << basenum1 << " " << basenum3 << endl; //基类的公有成员和保护成员,在派生类中 //可访问
}
};
int main()
{
Base b;
b.basenum1 = 10;
//b.basenum2 = 10; //在类的外部不可访问,private
//b.basenum3 = 15; //在类的外部不可访问,protected
b.setNum(14, 16, 17);
print(b);
b.getnum();
//在派生类的外部访问基类中的成员时,会根据继承方式影响基类成员的访问级别
//1.public 继承
Derived d;
d.basenum1 = 10; //public - public,可被访问
//d.basenum2 = 15; //private -- private,不可被访问
//d.basenum3 = 10; //protected -- protected,不可被访问
print(d);
//2.private 继承
Derived1 d1;
//d1.basenum1 = 15; //public -- private,不可被访问
//d1.basenum2 = 10; //private -- private,不可被访问
//d1.basenum3 = 20; //protected -- private,不可被访问
d1.print();
//3.protected 继承
Derived2 d2;
//d2.basenum1 = 10; //public -- protected,不可被访问
//d2.basenum2 = 16; //private -- private,不可被访问
//d2.basenum3 = 9; //protected -- protected,不可被访问
d2.print();
return 0;
}
这是vs输出:
这是qt输出:
能讲一下吗