在C ++中将一个类对象分配给另一个类对象 [英] assign one class object to another class object in c++

查看:222
本文介绍了在C ++中将一个类对象分配给另一个类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个类对象分配给c ++中的另一个类对象。

I want to assign one class object to another class object in c++.

Ex:
有一个类别的狗,另一个类别的猫。每个创建一个实例(d1& c1)。不想使用任何STL。我想在我的代码中使用此语句

Ex: There is one class Dog and another class Cat. Create one one instance of each (d1 & c1). Don't want to use any STL. I want to use this statement in my code


d1 = c1;

d1 = c1;

程序

class dog
{
    char  dc;
    float df;
    int   di;   
public:
    void setdata2(char c, float f, int i)
    {   dc = c; df = f; di = i; }
    void showdata2()
    {   cout  <<"char =" << dc <<", float =" << df <<", int =" << di  <<endl;   }
};


class cat
{
    float cf;
    int ci;
    char cc;    
public:
    void setdata(float f, int i, char c)
    {   cf = f; ci = i; cc = c; }
    void showdata()
    {   cout <<"float =" << cf <<", int =" << ci <<", char =" << cc  <<endl;    }
};


int main()
{
    dog d1, d2;
    cat c1, c2;

    d1.setdata2('A', 56.78, 30);
    c1.setdata(12.34, 2, 3);
    d1.showdata2();
    c1.showdata();

    d2 = c1;        // Question 1

    dog d3(c1);     // Question 2

    dog d4 = c1;    // Question 3

    return 0;
}

请回答 问题1/2/3 每个

Please answer Question 1/2/3 each separately.

推荐答案


我想将一个类对象分配给c ++中的另一个类对象。

I want to assign one class object to another class object in c++.

可以分配一个对象如果 A A B 类型的对象隐式转换 B ,而 B 可分配-或,如果 B 具有 接受类型为 A 类型的对象的赋值运算符。

It is possible to assign an object of type A to an object of type B if A is implicitly convertible to B, and B is assignable - or, if B has an overloaded assignment operator that accepts objects of type A.

有两种方法可以定义转换从自定义类型 A 到不相关的类型 B 。您可以为 A 定义转换函数。 code>,或者您可以为<$类型定义转换构造函数 c $ c> B

There are two ways to define a conversion from a custom type A to an unrelated type B. You can either define a conversion function for A, or you can define a converting constructor for type B.

1)这是副本分配。以上说明适用。定义 cat :: operator dog() dog :: dog(cat) dog :: operator =(cat)

1) This is copy assignment. The above explanation applies. Either define cat::operator dog() or dog::dog(cat) or dog::operator=(cat).

2)这是直接初始化。这不是您要的任务。定义隐式转换也可以这样做,但是重载的赋值运算符则不会。但是,重载的构造函数将是第三个替代方案。

2) This is direct initialization. It is not an assignment which is what you asked about. Defining an implicit conversion works for this as well, but an overloaded assignment operator will not. However, an overloaded constructor would be a substitute third alternative.

3)尽管从语法上看这有点像赋值,但这实际上是复制初始化。规则适用于2)。

3) Even though this looks a bit like assignment syntactically, this is actually copy initialization. Same rules apply as 2).

PS。请注意,您正在通过名称 d3 定义两个变量。那是一个错误。

PS. Note that you're defining two variables by the name d3. That is an error.

这篇关于在C ++中将一个类对象分配给另一个类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆