C++如何通过"constructor initialization"初始化行变量?
How does C++ initialize inline variable via "constructor initialization"?
我正在做教授在上次考试中给我的练习。
文本如下(其翻译,原文为意大利语(:
编写一个类模板
SmartP<T>
类型为T
的智能指针,这些指针重新定义了智能指针的赋值、复制构造函数和析构函数。模板SmartP<T>
必须包含一个允许编译以下代码的最小公共接口(具有较少数量的 menber(,执行将引发注释行
class C {
public:
int* p;
C(): p(new int(5)) {}
};
int main() {
const int a = 1;
const int *p = &a;
SmartP<int> r;
SmartP<int> s(&a);
SmartP<int> t(s);
cout << *s << " " << *t << " " << *p << endl; // 1 1 1
cout << (s == t) << " " << !(s == p) << endl; // 0 1
*s = 2;
*t = 3;
cout << *s << " " << *t << " " << *p << endl; // 2 3 1
r = t;
*r = 4;
cout << *r << " " << *s << " " << *t << " " << *p << endl; // 4 2 3 1
C c;
SmartP<C> x(&c);
SmartP<C> y(x);
cout << (x == y) << endl; // 0
cout << *(c.p) << endl; // 5
*(c.p) = 6;
cout << *(c.p) << endl; // 6
SmartP<C> *q = new SmartP<C>(&c);
delete q;
}
我的教授提供的解决方案如下:
template<class T>
class SmartP{
private:
T* ptr;
public:
SmartP(const SmartP& p) { p.ptr!=0 ? ptr(new T(*(p.ptr))) : ptr(nullptr); };
SmartP(const T* t = 0) { t!=0 ? ptr(new T(*t)) : ptr(nullptr); };
~SmartP() { delete ptr;}
T& operator*() const { return *ptr;}
bool operator==(const SmartP& p) const { return ptr == p.ptr;}
SmartP& operator=(const SmartP& p) {
delete ptr;
p.ptr!=0 ? ptr(new T(*(p.ptr))) : ptr(nullptr);
return *this;
}
};
但是当我尝试这样做时,我在每个"构造函数初始化"上都会收到一个错误,上面写着:
调用的对象类型"C*"不是函数或函数指针"(请注意,如果我删除 C 类,我会收到相同的错误,但在"C*"上有"int*"(。
所以我对此很感兴趣,我给它做了一些测试:
SmartP(const SmartP& p) : ptr(new T(*(p.ptr))) {}; //no error
SmartP(const SmartP& p) { ptr(new T(*(p.ptr))); }; //error
SmartP(const SmartP& p) { ptr = new T(*(p.ptr)); }; //no error
SmartP(const SmartP& p) {
if(p.ptr!=0){
ptr(new T(*(p.ptr))); //error
} else {
ptr(nullptr);
}
};
所以我的问题是C++如何通过"构造函数初始化"初始化内联变量?
为什么如果我正常初始化我的变量,它可以工作,但不能使用"构造函数初始化"?
>ptr(new T(*(p.ptr)));
此类成员初始化仅允许在其主体外部的构造函数(也称为成员初始值设定项列表(中使用。如果在构造函数主体中使用此行,则它是对名称为ptr
或ptr.operator()
的函数的调用。编译器说你完全一样,ptr
类型C*
既不是函数也不是函数对象。
只有两种方法可以初始化ptr
,所有这些方法都在第一行和第三行中,您将其标记为没有错误。
详细信息:构造函数和成员初始值设定项列表
相关文章:
- 为什么C++有不同的变量初始化方式?
- 静态 constexpr 成员变量初始化
- C++不同的变量初始化
- 全局和局部变量初始化与 constexpr 的差异背后的基本原理
- 是变量初始化失败吗?
- 视觉C++:在 DLL 加载期间,全局变量初始化顺序是否具有确定性?
- 类静态变量初始化顺序
- 使用 constinit 变量初始化 constexpr 变量
- 是否可以在不修改父类的情况下将成员变量初始化推迟到继承的类?
- 使用全局变量初始化不同编译单元中的其他全局变量
- 使用默认构造函数引用成员变量初始化错误
- 宏的 if 语句中的变量初始化
- 不稳定的C :每行适应性变化多变量初始化
- 同一函数中的静态函数变量初始化顺序
- C 语言中的静态变量初始化
- 错误:调用'begin(long double [nPoints])'没有匹配函数;使用硬编码的 int 与整数变量初始化向量
- 类POD成员变量初始化
- 尝试捕获类变量初始化的范围
- 共享库中 __attribute__((构造函数)) 的全局/静态变量初始化问题
- 多变量初始化编译器支持