#include <iostream>
#include <string.h> // strlen, strcpy
Here we have the Base class with a non-default ctor, a getter for name and its destructor.
class Base {
char *name_;
public:
Base(const char* str)
: name_{new char[strlen(str)]}
{
strcpy(name_,str);
}
char * name() const
{
return name_;
}
virtual ~Base()
{
delete [] name_;
}
};
Derived class inherits from Base publicly and has its own non-default ctor.
class Derived : public Base {
public:
Derived(const char* str)
: Base(str){}
};
My question is how do I make the last line of code in main to work?
int main()
{
char d1name[] {"d1"};
Derived d1(d1name);
std::cout << d1.name() << std::endl;
d1.name[0] = 'D';
}
My question is how do I make the last line of code in main to work?
Just add parenthesis to call the getter
d1.name()[0] = 'D';
// ^^
But in general that's a not so good idea. You could make the char
array in your base class public
then, or even better use a std::string
at all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.