正确的语法,用于在C 中继承,并具有初始化列表和内存分配

Correct Syntax for Inheritance in C++ with initialize list and memory allocation?

本文关键字:初始化 列表 内存 分配 语法 用于 继承      更新时间:2023-10-16
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;
};