【问题标题】:C++ class not printing? [closed]C++ 类不打印? [关闭]
【发布时间】:2019-04-11 17:37:37
【问题描述】:

我有点困惑为什么这不打印名字! 我有一个human.cpp:

#include <string>
#include <iostream>
#include "human.h"

human::human(int age, human *n){
m_age=age;
name = new char[2];

human::~human() = default;

void human::printDetails(){
    std::cout <<"name is      " << name << " age is " << m_age << std::endl;
}

和human.h:

class human {
    public: //: needed
        human(int age, human *name);
        ~human();
        void printDetails();
    private :
        char *name;
        int m_age;

};

最后是 main.cpp:

#include <iostream>
#include <string>
#include "human.h"

int main()

{
    human *Alex = new human(10, Alex); //pointer // needs argument //should have both age and name
    Alex->printDetails(); //print not Print

    }

所以我的问题是:它打印年龄,但不打印姓名?有什么建议?谢谢:)

【问题讨论】:

标签: c++ class


【解决方案1】:

我猜你对human 构造函数的第二个参数感到困惑。看看这个变化:

人类.h

class human {
public:
    human(int age, char *name);
    human(const human& h);
    human& operator=(const human& h);
    void printDetails();
    virtual ~human();
private:
    int age;
    char *name;
};

人类.cpp

human::human(int _age, char *_name) {
    age = _age;
    name = new char[strlen(_name)+1];
    strcpy(name, _name);
}

human::human(const human& _h) { //Copy constructor
    age = _h.age;
    name = new char[strlen(_h.name)+1];
    strcpy(name, _h.name);
}

human& human::operator=(const human& _h) { //Copy assignment operator
    age = _h.age;
    name = new char[strlen(_h.name)+1];
    strcpy(name, _h.name);
    return *this;
}

void human::printDetails(){
    std::cout <<"name is " << name << " age is " << age << std::endl;
}

human::~human() { //Destructor
    delete[] name;
}

main.cpp

int main() {

    human *alex = new human(10, "Alex");
    alex->printDetails();

    human *anotherAlex = new human(*alex);
    anotherAlex->printDetails();

    delete alex;
    delete anotherAlex;
}

一个建议:我会使用Human 作为类名,使用alex 作为变量名。 (看看我是如何大写的)

【讨论】:

  • @Swordfish 你能告诉我更多吗。是关于我如何使用strcpy吗?
  • 直到一次缓冲区溢出(您想将 5 chars 的“Alex”复制到缓冲区 2 chars 大)和最后一次编辑时出现 1 次内存泄漏。 (并且您的头像侵犯了一项版权;p)
  • @Emadpres 复制 ctor 和赋值应该有 const human& _h 参数
  • @Emadpres 您还需要更改 copy-ctor 和 assignment-operator 的定义。
【解决方案2】:

您的代码中不需要任何new。由于您在代码中 #included &lt;string&gt; 我假设您想使用它:

#include <string>
#include <iostream>

class Person
{
    int age;
    std::string name;

public:
    Person(int age, std::string name)
    : age  {  age },
      name { name }
    {}

    int get_age() const { return age; }
    std::string const& get_name() const { return name; }

    void print_details() const {
        std::cout << "My name is " << name << ". I am " << age << " years old.\n";
    }
};

int main()
{
    Person p{ 19, "Alex" };
    p.print_details();
}

如果你*真的*想以艰难的方式做到这一点tm

#include <cstring>  // std::strlen()
#include <utility>  // std::exchange(), std::swap()
#include <iostream>

class Person
{
    char *name_;
    int   age_;

public:
    Person(int age, char const *name)  // constructor
                       // we don't want to call std::strlen() on a nullptr
                       // instead allocate just one char and set it '\0'.
    : name_ { new char[name ? std::strlen(name) + 1 : 1]{} },
      age_  { age }
    {
        if (name)
            std::strcpy(name_, name);
    }

    Person(Person const &other)  // copy-constructor
    : name_ { new char[std::strlen(other.name_) + 1] },
      age_  { other.age_ }
    {
        std::strcpy(name_, other.name_);
    }

    Person(Person &&other) noexcept  // move-constructor
    : name_ { std::exchange(other.name_, nullptr) },  // since other will be
      age_  { other.age_ }                            // wasted anyway, we
    {}                                                // "steal" its resource

    Person& operator=(Person other) noexcept  // copy-assignment operator
    {                                   // since the parameter other got
        std::swap(name_, other.name_);  // copied and will be destructed
        age_ = other.age_;              // at the end of the function we
        return *this;                   // can simply swap  the pointers
    }                                   // - know as the copy&swap idiom.

    ~Person() { delete[] name_; }  // destructor

    void print_details() const
    {
        std::cout << "I am " << name_ << ". I am " << age_ << " years old.\n";
    }
};

int main()
{
    Person p{ 19, "Alex" };
    p.print_details();
}

如果您不想实现特殊的成员函数,则必须= delete; 它们,这样编译器生成的版本(对于管理自己的资源的类将无法正常工作)不会被调用意外。

【讨论】:

    【解决方案3】:
        #include <iostream>
        #include <cstring>
        #include <new>
    
        using namespace std;
    
        class human {
            public: 
                human(int age, const char * name)
                {
                    m_age=age;
                    m_name = new char[strlen(name)+1];
                    strcpy(m_name,name);
                }
                ~human()
    {
    delete[] m_name;
    }
                void printDetails()
                {
                    std::cout <<"name is      " << m_name << " age is " << m_age << std::endl;
                }
            private :
                char *m_name;
                int m_age;
    
        };
    
        int main()
        {
    
            human *Alex = new human(10, "alex"); //pointer // needs argument //should have both age and name
            Alex->printDetails(); //print not Print
            delete Alex;
            return 0;
        }
    

    您需要阅读更多内容。您分享的示例在许多层面上都是错误的,还阅读了有关动态内存管理的信息。

    【解决方案4】:

    对于初学者,你可以使用 std::string,所以你已经包含了它。 ))

    人类.h

    #include <string>
    class human
    {
        public: //: needed
            human(int age, std::string name);
            void printDetails();
        private :
            std::string name;
            int m_age;
    };
    

    人类.cpp

    #include <iostream>
    #include "human.h"
    
    human::human(int age, std::string n)
    {
        m_age = age;
        name = n;
    }
    
    void human::printDetails()
    {
        std::cout <<"name is: " << name << " age is: " << m_age << std::endl;
    }
    

    main.cpp

    #include "human.h"
    
    int main()
    
    {
        human *Alex = new human(10, "Alex");
        Alex->printDetails();
    
    }
    

    【讨论】:

    • 一次内存泄漏,不合理地使用动态内存分配和指针,没有使用初始化列表。为什么特别“初学者”使用std::string
    • 这是作者的一个例子,我回答了他的问题。 std :: string 的发明是因为使用 char * 不方便,对于初学者来说更是如此。为什么要减去正常有意义的答案?
    • 我没有投反对票。
    • 我看了你的回答,对于一个新手到一个新手新手,但那里的问题并不比作者的问题少。没有人可以写信给你,因为评论需要 50 分,像你这样的人不会让别人举起它)))
    • “我看了你的回答,[...],但那里的问题并不比作者的问题少。”有哪些问题? “像你这样的人不让人举起它”像我这样的人?再说一遍:我没有否决你的回答。
    猜你喜欢
    • 2015-12-02
    • 2010-09-30
    • 2011-07-30
    • 1970-01-01
    • 2022-06-15
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    相关资源
    最近更新 更多