Using pointers with classes in C++ [closed]

2019-03-07 03:39发布

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;
};

3条回答
趁早两清
2楼-- · 2019-03-07 04:01

I would suggest reading an introductory book on C++, "C++ Primer (4th Edition)" by Lippmann et al. or finding an on-line tutorial on C++. The problem you are solving requires more understanding than can be related in an SO Q and A.

查看更多
对你真心纯属浪费
3楼-- · 2019-03-07 04:02

Please take a look at my code and suggest how I change the code in the class definition, not main.

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

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.

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.

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..." ));

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).

查看更多
小情绪 Triste *
4楼-- · 2019-03-07 04:19

I guess, it's the

virtual void speak( );

in

cout << "The " << "..." << p->speak( ) << endl;

which causes the error message. You cannot output a void value to std::ostream.

Presumably, it should have been

virtual std::string speak();
查看更多
登录 后发表回答