问题描述
我有两个文件。一个是测试文件,另一个是头文件,上面带有链表类的声明。此类具有一些内联方法。这段代码不是我的。
我不理解的是测试文件中的一行显示x.info() = 1515;
。我们怎么能打这样的电话?如果可以访问此方法的定义,我本可以弄清楚这一点,但是这里不是这种情况。如果有人可以帮助我了解这里发生的事情,我将不胜感激。
代码如下:
ListeInt.hpp
#ifndef _LISTEINT_H_
#define _LISTEINT_H_
#include <exception>
#include <stdexcept>
class ListeInt {
public:
inline constexpr bool vide () const noexcept;
inline int info () const;
inline const ListeInt& suite () const;
}; // ListeInt
#include <ostream>
std::ostream& operator<< (std::ostream&,const ListeInt&);
#endif // _LISTEINT_H_
main.cpp
#include "ListeInt.hpp"
#include <utility> // swap,move,forward...
#include <exception>
#include <iostream> // cin,cout,clog,cerr...
int main () {
std::cout << std::boolalpha << "<<<" << std::endl;
{
std::cout << "***" << std::endl;
int i = 42;
ListeInt x;
std::cout << "sizeof(x) = " << sizeof(x)
<< " cf. " << sizeof(nullptr) << std::endl;
std::cout << "x = " << x << std::endl;
std::cout << "x.vide = " << x.vide() << std::endl;
x = ListeInt(i);
std::cout << "x = " << x << std::endl;
std::cout << "x.vide = " << x.vide() << std::endl;
std::cout << "x.info = " << x.info() << std::endl;
std::cout << "x.suite = " << x.suite() << std::endl;
x.info() = 1515;
std::cout << "x = " << x << std::endl;
std::cout << "x.info = " << x.info() << std::endl;
}
std::cout << ">>>" << std::endl;
return 0;
}
解决方法
如果代码完全编译了(出于某些原因它没有编译),则语句x.info() = 1515;
实际上什么也没做。
调用x.info()
将返回一个临时int
,然后代码将尝试为该临时实例分配一个1515
的值。当到达;
时,该临时变量将被丢弃。 x
的状态将不受此分配的影响。
我说“ would”,因为该语句是代码无法正确编译以开头的原因之一:
error: lvalue required as left operand of assignment x.info() = 1515; ^~~~
如果x.info()
返回对int
对象内存在的x
的引用,情况将有所不同。但这不是事实。
因此,编写此代码的人都不知道他们在做什么,或者您使用的是错误的ListeInt.hpp
版本。