【问题标题】:input on reference or on pointer return type functions引用或指针返回类型函数的输入
【发布时间】:2013-12-27 17:37:11
【问题描述】:

我已经编写了以下代码,但我不太清楚它为什么会起作用。

#include<iostream>
#include<cstring>
using namespace std;
class temp_class
{
private:
    char id[20];
    char name[20];
    float price;
public:
    temp_class();
    char*getid();
    char*getname();
    float&getprice();
    void print()const;
};
temp_class::temp_class()
{
    strcpy(id,"unknown");
    strcpy(name,"unknown");
    price=0.0;
}
char*temp_class::getid(){return id;}
char*temp_class::getname(){return name;}
float&temp_class::getprice(){return price;}
void temp_class::print()const
{
    cout<<"ID : "<<id<<" / Name : "<<name<<" / Price : "<<price<<endl;
}
int main()
{
    int i=0;
    int n=0;
    cout<<"Enter Number of Items : ";
    cin>>n;
    temp_class*T=new temp_class[n];
    for(;i<n;i++)
    {
        cout<<"Enter ID,Name,and price for Item "<<i+1<<" : ";
        cin>>T[i].getid()>>T[i].getname()>>T[i].getprice();//the user will input on the 
    }                                                    //returned data members 
    for(i=0;i<n;i++)                                        //but why it worked ?
    { 
        T[i].print();
    }
    return 0;
}

所以我认为使它起作用的原因是因为 float&getprice() 通过引用返回价格,因此对其进行的输入将影响它的内存位置,char*getid() 返回指向 id 的第一个内存单元的指针并且默认情况下对数组的更改将生效,因为它是通过引用发送的(默认情况下),我认为对于 char*getname() 也是如此;

【问题讨论】:

  • 你的问题是?
  • 我认为你最好使用std::string而不是char*/char[]

标签: c++ class pointers input reference


【解决方案1】:

你的假设是正确的。 getprice() 返回对类成员的引用,然后调用者可以修改该引用。对于char*,有一个特殊的重载将它们视为字符串。由于仅按值返回指向实际字符串的指针,因此可以再次修改实际字符串。

如果您想避免这种行为,您可以在返回值中添加 const 关键字

【讨论】:

    猜你喜欢
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    相关资源
    最近更新 更多