C++ 中进行链式调用的对象类型应该是什么

问题描述 投票:0回答:2

有人可以告诉我 Class Point 和 Class Dog 这两个代码有什么区别吗?类dog编译没有任何错误。如果未通过指针调用堆栈中的点对象,则 Point 类会引发错误。为什么?

#include <iostream>
#include<string_view>
#include<string>

class Dog{
    public : 
    
        Dog() = default;
        Dog(std::string_view name_param, std::string_view breed_param, int  age_param){
            name = name_param;
            breed = breed_param;
            p_age = new int;
            *p_age = age_param;
    
        }
        void print_info(){
            std::cout << "Dog (" << this << ") : [ name : " << name 
                << " breed : " << breed << " age : " << *p_age << "]" << std::endl;
        }

        //Setters
        //Chained calls using pointers
        
        Dog* set_dog_name(std::string_view name){
            //name = name; // This does nothing
            this->name = name;
            return this;
        }
        Dog* set_dog_breed(std::string_view breed){
            this->breed = breed;
            return this;
        }

        Dog* set_dog_age(int age){
            *(this->p_age) = age;
            return this;
        }
        

    private : 
        std::string name;
        std::string breed;
        int * p_age{nullptr};
};


int main(){

    Dog dog1("Fluffy","Shepherd",2); //Constructor
    dog1.print_info();

    //Chained calls using pointers
    dog1.set_dog_name("Pumba")->set_dog_breed("Wire Fox Terrier")->set_dog_age(4);

    dog1.print_info();

    std::cout << "Done!" << std::endl;
   //Destructor
    return 0;
}
#include<iostream>

class Point{
    public : 
    
    Point() = default;
    Point(double x, double y){
        m_x = x; 
        m_y = y;
    }
    
    void print_point(){
    std::cout << "Point[x : " << m_x << ", y : " << m_y << "]" ;
    }

    Point * set_x(double m_x){
        this->m_x = m_x;
        return this;
    }

    Point* set_y(double m_y){
        this->m_y = m_y;
        return this;
    }

    //member variables
    private : 
    double m_x{1};
    double m_y{1};
};

int main(){
    
    Point p1(1.1, 2.2);
    //Point* p_ptr {&p1}; 
    p1.print_point();
    p1->set_x(21.2)->set_y(4.2); //error.error: base operand of ‘->’ has non-pointer type ‘Point’                                      
    p1.print_point();            //works only if p_ptr->set_x(21.2)->set_y(4.2);
    return 0;
}

我不明白为什么 Dog 类可以使用常规对象,但 point 类需要一个指针。请帮忙!!

c++ pointers call chained
2个回答
1
投票

p1
是一个对象,而不是指向对象的指针。因此,您可以使用点运算符来访问成员和成员函数。如果对象不是指针或没有重载箭头运算符,则无法在对象上使用箭头运算符。

如果您想要流畅的 getter,我建议您通过引用返回而不是通过指针返回,即

return *this;


0
投票

正如 Eljay 在评论中提到的,您在两个示例中以不同的方式取消引用初始变量。原始 Dog 局部变量与“.”一起正确使用第一次调用的符号,然后是后续调用的指针“->”符号。 Point 从一开始就使用指针“->”表示法,导致此错误。

© www.soinside.com 2019 - 2024. All rights reserved.