本文介绍了在C ++中使用类的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉创建类和使用点符号来访问对象的函数。我不熟悉的做法相同,但用指针的符号。请查看我的代码,并建议如何更改类定义中的代码, main。

I am familiar with creating classes and using dot notations to access functions for the objects. I am unfamiliar with the notation of doing the same but with pointers. Please take a look at my code and suggest how I change the code in the class definition, not main.

main:

Pet * p = new Pet( "Sunset", "Cat", "meow..." );

cout << "The " << p->getVariety( ) << " " << p->getName( ) << " speaks by saying " << p->spea( ) << endl;

class:

class Pet
{
public:
Pet( );
Pet( std::string name, std::string variety, std::string says )
{
    using namespace std;
    myName = name;
    myVariety = variety;
    howIspeak = says;
}

std::string getName( ) const
{
    return myName;
};
std::string getVariety( ) const
{
    return myVariety;
};

virtual void speak( );

protected:
std::string myName;
std::string myVariety;
std::string howIspeak;
};


推荐答案

使用命名空间std; 在这里没有用,只是删除它。

The using namespace std; is useless in there, just remove it.

然后,您将拥有虚拟方法和 protected 成员,这意味着你愿意从该类继承:或者不定义一个 virtual 析构函数。

Then, you are having virtual methods and protected members, which suggests that you are willing to inherit from that class: either don't or define a virtual destructor as well.

此外,从main调用的成员函数返回 void 类型,您要传递给运算符<的 std :: cout 。

Also, the speak member function you are calling from the main, returns void, which is not a type you want to pass to operator<< of std::cout.

最后:为什么要使用 nake指针和动态分配?不要使用它,除非你是绝对强制,甚至然后,使用 std :: shared_ptr 或 std :: unique_ptr (或任何其他智能指针系列):

And finally: why are you using nake pointers and dynamic allocation? Don't use it unless you are absolutely forced to, and even then, use std::shared_ptr or std::unique_ptr (or any other of the smart pointers family) instead:

std::unique_ptr<Pet> ptr(new Pet( "Sunset", "Cat", "meow..." ));

之后, ptr 像任何其他指针,除非它会清理自己(将调用 delete )当你完成它(当它离开范围)。

After that line, ptr will behave almost like any other pointer, except it will clean himself up (will call delete) when you are done with it (when it leaves the scope).

这篇关于在C ++中使用类的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 19:26