C++类的继承中:子类构造函数初始化从父类继承过来的成员数据

1. 可行方法:

#include <iostream>
#include <string>

using namespace std;

//父类
class A {
public:
	string s;
};

//子类
class B :public A {
	B(string str){
		A::s = str; //ok
		this->s = str;//ok
	}
};

int main() {
	return 0;
}

2. 错误方法:

#include <iostream>
#include <string>

using namespace std;

//父类
class A {
public:
	string s;
};

//子类
class B :public A {
	B(string str) : s(str) {}//注意,此处,s(str)报错!!!
};

int main() {
	return 0;
}
发布了71 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qionggaobi9328/article/details/104988546
今日推荐