axi*_*xis 3 c++ inheritance initializer-list
下面的代码被编译在 g++ 4.6.3 for Linux
#include <iostream>
class A {
public:
int x;
std::string c;
A(int x,std::string c):x(10),c("Hi"){
}
~A(){
std::cout << "Deleting A()" << std::endl;
}
};
class B : public A {
public:
B():A(20,"Hello"){
}
~B(){
std::cout << "Deleting B()" << std::endl;
}
};
int main(){
B o;
std::cout << o.x << std::endl;
std::cout << o.c << std::endl;
return(0);
}
Run Code Online (Sandbox Code Playgroud)
但它没有做应该做的事情,类型 B 无法更改它从 A 继承的那 2 个变量的值。
关于为什么这不能正常工作的任何解释?
您的基本构造函数采用这些值……并完全无视它们!
改变这个:
A(int x,std::string c):x(10),c("Hi"){}
Run Code Online (Sandbox Code Playgroud)
对此:
A(int x,std::string c):x(x),c(c){}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10678 次 |
| 最近记录: |