正确的语法,用于在C 中继承,并具有初始化列表和内存分配
Correct Syntax for Inheritance in C++ with initialize list and memory allocation?
class shape{
public:
shape(string a, bool b):name(new string), moral(new bool){
*name=a;
*moral=b;
}
shape():name(new string),moral(new bool){
*name="shape";
*moral=true;
}
~shape(){
delete name;
delete moral;
}
protected:
string* name;
bool* moral;
};
class circle:public shape{
public:
circle(string s, bool bb, double d):shape(new string, new
bool),radius(new double){
}
protected:
double * radius;
};
最近,我试图拿起C 。这是我在学习继承属性时编写的示例代码。在"形状(新字符串,新布尔)"中显示了错误的错误。我不确定什么是正确的语法。另外,我注意到如果在类中使用指针,则使用初始化列表的形式分配内存而不是分配值。我可以使用更好的表达方式和语法吗?谢谢你们。
更喜欢交易值。C 不像Java或C#。避免使用此类物品的新指针,新的和删除。
如果您不编写攻击函数,则编译器为您提供正确的破坏者。免费副本和移动。
#include <string>
class shape{
public:
shape(std::string a, bool b) : name(a), moral(b)
{
}
shape():name("shape"),moral(true){
}
protected:
std::string name;
bool moral;
};
class circle:public shape{
public:
circle(std::string s, bool bb, double d)
: shape(s, bb)
, radius(d)
{
}
protected:
double radius;
};
但是在实际类中,我想使用动态内存进行存储:
#include <string>
#include <memory>
class shape{
public:
shape(std::string a, bool b)
: name(std::make_unique<std::string>(a))
, moral(b)
{
}
shape()
: shape("shape", true)
{
}
protected:
std::unique_ptr<std::string> name;
bool moral;
};
class circle:public shape{
public:
circle(std::string s, bool bb, double d)
: shape(s, bb)
, radius(d)
{
}
protected:
double radius;
};
相关文章:
- C++类 - 初始化列表 - 递归 - 按值传递
- 在初始化列表之外手动调用基类的构造函数
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- std::map与谓词与初始化列表
- 类内初始化与构造函数初始化列表的顺序
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- C++初始化列表与分配值
- C++初始化列表中的向量集大小或调整大小
- 在构造函数初始化列表中使用 std::variant
- emplace_back初始化列表错误,当初始化列表在独立变量上工作时
- 解释了构造函数成员初始化列表
- 使用初始化列表时如何获取私有数据?
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- 如何在成员初始化列表中声明共享指针
- 庞大的初始化列表,如何修复"fatal error C1060: compiler is out of heap space"
- 我可以检查初始化列表中设置的构造函数主体中的变量吗
- 使用整数初始化列表初始化长双精度的向量
- 是否可以在C++中使用初始化列表设置数组的特定成员?