提问人:Manobhav Pandey 提问时间:10/20/2017 最后编辑:MABVTManobhav Pandey 更新时间:10/20/2017 访问量:3124
C++:按值将对象传递给同一类的成员函数
C++: Passing objects by value to a member function of the same class
问:
我是C++的初学者,我刚刚开始学习OOP。在下面的程序中,我添加了相同类的对象并显示了结果。但是,我无法理解这样一个事实,即如果我按值将对象传递给函数,那么更改如何反映在调用函数中。该函数需要类 Complex 的两个对象,用于调用函数 () 的对象被隐式传递给该函数,但是调用函数中的值和影响如何,因为无法访问它们在内存中的“位置”。任何帮助将不胜感激!addNumbers()
c3.addNumbers(c1, c2)
c3.real
c3.imaginary
addNumbers()
提前致谢!
class complex {
private:
int real;
int imaginary;
public:
/* Using member initializers to assign values to members */
complex()
: real(0)
, imaginary(0)
{}
void readData(int x, int y);
void printData();
void addNumbers(complex, complex);
};
void complex::readData(int x, int y)
{
real = x;
imaginary = y;
}
void complex::printData()
{
cout << real << "+" << imaginary << "i" << endl;
}
void complex::addNumbers(complex c1, complex c2)
{
real = c1.real + c2.real;
imaginary = c1.imaginary + c2.imaginary;
}
int main(void)
{
complex c1, c2, c3;
c1.readData(-5,17);
c2.readData(11,7);
c3.addNumbers(c1,c2);
c3.printData();
return 0;
}
答:
调用 时,隐式接收指向 not 的副本的指针。此指针可以与关键字一起显式使用。c3.addNumbers(c1, c2))
addNumbers
c3
c3
this
所以你的函数可以这样重写:
void complex::addNumbers(complex c1, complex c2)
{
this->real = c1.real + c2.real;
this->imaginary = c1.imaginary + c2.imaginary;
}
这严格等同于您的原始函数。addNumbers
换言之:每次在成员函数中使用类成员时,都会在该成员前面附加一个隐式;因此,如果 是类成员,则始终等价于类成员函数内部。this->
member
member
this->member
虚数和实数是私有属性,但它们可以通过成员函数(也称为对象的方法)访问。当执行 c3.addNumbers (c1, c2) 语句时,它将等效于以下两个语句:
c3.real = c1.real + c2.real;
c3.虚构 = c1.虚构 + c2.虚构
我们可以访问 c3.real 和 c3.imaginary 的原因是因为 addNymbers () 函数是 Complex 类的成员。
我在您的原始代码中做了一些评论,以解释为什么真实和虚构在下面受到影响。(查找 //MABVT)
另外: 我将为您提供另一个有用的示例,以进一步进步!
回顾
class complex {
private:
int real;
int imaginary;
public:
/* Using member initializers to assign values to members */
complex()
: real(0)
, imaginary(0)
{}
void readData(int x, int y);
void printData();
// MABVT: You provide two complex numbers which you want to add
// together!
void addNumbers(complex, complex);
};
void complex::readData(int x, int y)
{
real = x;
imaginary = y;
}
void complex::printData()
{
cout << real << "+" << imaginary << "i" << endl;
}
void complex::addNumbers(complex c1, complex c2)
{
// MABVT: Use c1.component and c2.component, add them up and store them
// in this class' instance.
real = c1.real + c2.real;
imaginary = c1.imaginary + c2.imaginary;
// MABVT: c3.real and c3.imaginary are affected at this exact location
// since you overwrite the values with the addition-results.
// Since the function addNumbers(complex, complex) is invoked
// on the complex instance 'c3', real and imaginary of c3 are
// known in this context, and consequently you can use them.
//
// To attach to your statement that the c3 instance's pointer is
// implicitly passed:
// Yes it is passed as the first parameter invisibly as
// 'complex* this'
//
// So you could also write:
// this->real = c1.real + c2.real; (see the use of this?)
}
int main(void)
{
complex c1, c2, c3;
c1.readData(-5,17);
c2.readData(11,7);
c3.addNumbers(c1,c2);
c3.printData();
return 0;
}
另类
// Example program
#include <iostream>
#include <string>
class Complex { // Give class names capital first letter
private:
int m_real; // Just a recommendation: I'd like to be able to distinguish parameter for member in the identifier already!
int m_imaginary; // Just a recommendation: I'd like to be able to distinguish parameter for member in the identifier already!
public:
/* Using member initializers to assign values to members */
inline Complex() // Inline it, if you define this class in a header and reuse it multiple times...
: m_real(0)
, m_imaginary(0)
{}
// Provide initializing constructor to be able to construct
// a complex number quickly. Replaces your readData(...);
inline Complex(
int inRealPart,
int inImaginaryPart)
: m_real(inRealPart)
, m_imaginary(inImaginaryPart)
{}
// Getters to read the values
inline int real() const { return m_real; }
inline int imaginary() const { return m_imaginary; }
void printData();
// Local assignment-add operator to add another complex
// to this specific instance of complex and modify the internal
// values. Basically what you did as the second part of addNumbers.
Complex& operator+=(const Complex& r);
};
void Complex::printData()
{
std::cout << m_real << "+" << m_imaginary << "i" << std::endl;
}
// Member add-assign operator definition adding this instance and another instance 'r' by adding up the values and storing them in the instance this operator is called on.
Complex& Complex::operator +=(const Complex& r)
{
std::cout << "Local" << std::endl;
this->m_real += r.real();
this->m_imaginary += r.imaginary();
return *this;
}
// Static global operator+ definition, taking two values and creating a
// third, NEW one initialized with the results.
// This was the first part of addNumbers
static Complex operator+(const Complex& l, const Complex& r) {
std::cout << "Static Global" << std::endl;
return Complex(
(l.real() + r.real()),
(l.imaginary() + r.imaginary())
);
}
int main(void)
{
// Same as before
Complex c1(-5, 17);
Complex c2(11, 7);
Complex c3(1, 2);
// Test output
c1.printData();
c2.printData();
c3.printData();
std::cout << std::endl;
Complex c3 = (c1 + c2); // Calls static global and c3 is overwritten with the result. Exactly like your addNumbers call
c1 += c2; // instance local, will change c1's internal values ( see print out below )
Complex c5 = ::operator+(c1, c2); // Static global, c5 is initialized with the result. Exactly like your addNumbers call
std::cout << std::endl;
c1.printData();
c2.printData();
c3.printData();
c5.printData();
return 0;
}
这对初学者来说应该很多。
一些解释
静态全局运算符重载与本地运算符重载
阅读主题:http://en.cppreference.com/w/cpp/language/operators
您使用的所有运算符(+、-、*、/、%、+=、-=、...)都只是函数,这些函数是为基元类型预定义的,并由 libstd 为 STD 类型提供。
不过,您可以覆盖/定义它们。
我通过两种方式做到了这一点:
静态全局运算符+:
接受两个任意 Complex 实例并添加其组件。 最后,创建一个 NEW 实例,并使用结果进行初始化。
基本上这只是一个静态函数,它链接到“+”的 编译器。
和:
本地成员运算符+=:
接受 Complex 的另一个实例,并将其组件值添加到 调用运算符的实例的组件值:'l += r -> 调用 l,其值将通过添加 r' 的值来修改
必须定义所有运算赋值运算符(+=、-=、*=、/= 等) 在类中,既不能是全局的,也不能是静态的。
const 类型&
阅读有关 const 的更多信息:https://www.cprogramming.com/tutorial/const_correctness.html
对任何类型的实例的常量引用将确保两件事:
- &:您只复制地址,但通过这种方式,您的函数可以更改所有公共值或调用大多数函数。
- const:实例不可修改,无法更改任何内容
结合起来,这意味着:您不必复制实例(按值传递),而只需提供其地址引用(按引用传递)。通常,这会提高性能,尤其是当您传递大型复杂对象时。
评论