2017-09-15 79 views
-2
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++中的继承的正确语法,初始化列表和内存分配?

+3

为什么你使用'名:(新字符串)',而不仅仅是'名称:(一)'? – Barmar

+0

名称是我创建的指针。对于动态内存,我不应该先分配内存吗? –

+0

为什么你需要它是动态的?为什么不只是'string'作为成员而不是'string *'? – Barmar

回答

1

喜欢交易价值。 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; 
}; 
+0

那么,我知道如何处理值,但指针,这就是为什么我问是否有正确和简单的语法在类中使用动态内存,特别是在处理继承时。 –

+0

@天元ok将更新以展示带智能指针的动态内存 –